import React, { Component, Fragment } from 'react';
import { connect } from 'dva';
import router from 'umi/router';
import { Card, Button, message, Spin,Form,Select } from 'antd';
import SelectPath from '@/components/plugins/selectPath/index';
import { Design } from 'zent';
import configConf from '../../store/microPage/config/index';
import ConfigEditor from '../../store/microPage/config/ConfigEditor';
import whitespaceConf from '../../store/microPage/whitespace/index';
import lineConf from '../../store/microPage/line/index';
import richtextConf from '../../store/microPage/richtext/index';
import imageAdConf from '../../store/microPage/imagead/index';
import videoConf from '../../store/microPage/video/index';
import imagenavConf from '../../store/microPage/imagenav/index';
import storebanner from '../../store/microPage/storebanner/index';
import imageHotArea from '../../store/microPage/imageHotArea/index';
import product from '../../store/microPage/product/index';
import coupon from '../../store/microPage/coupon/index';
import 'zent/css/index.css';
import 'zent/css/design-config.css';
import 'zent/css/design-whitespace.css';
import 'zent/css/design-line.css';
import 'zent/css/design-image-ad.css';
import SelectWidthAction from '@/components/SelectWidthAction/index';
import styles from './index.less';

const { Option } = Select;
const namespace = 'micropage';
const groupedComponents = [
  Object.assign({}, configConf, {
    dragable: false, // 是否可以拖拽
    appendable: false, // 是否出现在底部的添加组件区域
     editable: false,// 是否可以编辑，UMP里面有些地方config是不能编辑的
    configurable: false,
    highlightWhenSelect: false,
  }),
  Design.group('基础组件'),
  richtextConf,
  imageAdConf,
  imagenavConf,
  coupon,
  Object.assign({ limit: 1 }, storebanner),
  videoConf,
  imageHotArea, // 热区
  Design.group('其他组件'),
  whitespaceConf,
  lineConf,
  product
];

@Form.create()
class Simple extends Component {
  state = {    
    value: [
      {
        type: configConf.type,
        ...ConfigEditor.getInitialValue(),
      },   
    ],
    loading:false
  };

  componentDidMount(){
    const { value } = this.state;
    window.Isoption = true;  
  }

  componentWillMount() {
    window.Isoption = false;
    const { dispatch, match } = this.props;
    const { value } = this.state;
    console.log(match.params)
    const id = match.params.id ? match.params.id / 1 : 0;
    this.requestTempList();         
  }

  requestTempList = (type) => {
    const { dispatch } = this.props;
    dispatch({
        type: `productDetailTemplate/FindTemplateList`,       
        callback: {
            success:()=>{
              if(type==1){
                message.success('已刷新')
               } 
            }
        }
    })
  }

  onChange = newValue => {
    console.log(newValue)
    
    this.setState({
      value: newValue,
    });
  };
  
  saveDesign = instance => {
    this.design = instance && instance.getDecoratedComponentInstance();
  };

  cancel = () => {
    router.replace(
        {
          pathname: `/${window.storeId}/goods/detailtemplates`,
        }                   
      );
  }

  submit = () => {
    this.triggerDesignValidation()
      .then(() => {
        const { dispatch,match } = this.props;
        const { value } = this.state;        
        const datajson = value;        
        const clonedata = { name:value[0].name, jsonData: JSON.stringify(datajson), id: match.params.id>0?match.params.id/1:0 };
        console.log(clonedata)        
       return;
        dispatch({
          type: 'productDetailTemplate/UpdateTemplate',
          payload: clonedata,
          callback: {
            success: res => {
              if (res.Code === 0) {
                message.success('提交成功');
                setTimeout(() => {
                  router.replace(
                    {
                      pathname: `/${window.storeId}/goods/detailtemplates`,
                    }                   
                  );
                });
              } else {
                message.error(res.Msg);
              }
            },
          },
        });
        this.design.markAsSaved();
      })
      .catch(validations => {
        console.log(validations);
      });
  };

  triggerDesignValidation() {
    return this.design.validate();
  }

  reload = () =>{
    this.requestTempList(1);
  }

  addTemp = () => {
    router.replace(
        {
          pathname: `/${window.storeId}/goods/detailtemplates`,
        }                   
      );
  }

  render() {
    const {  value,loading } = this.state;
    const { submitLoading,allTempList } = this.props; 
    const { getFieldDecorator } = this.props.form;      
    const actions=[
        this.reload,
        this.addTemp
    ];      
    const formItemLayout = {
        labelCol: {
            xs: { span: 5 },
            sm: { span: 5 },
            md: { span: 5 },

        },
        wrapperCol: {
            xs: { span: 19 },
            sm: { span: 19 },
            md: { span: 19 },
        },
    };
    return (
      <Fragment>
        <Spin spinning={ loading}>
          <Card>          
            <div className="xkd-mb16">
                <Form layout="inline" onSubmit={this.handleSubmit}>
                    <Form.Item label="商品页模板"  style={{width:400}} {...formItemLayout} className={styles.SelectItem}>
                    {/* {getFieldDecorator('price', {
                        initialValue: [{Id:1,Name:'dfsd'}],
                        //actionText:['刷新','新建模板']
                       // rules: [{ validator: this.checkPrice }],
                    })(<SelectWidthAction actionText={['刷新','新建模板']} actions={actions}/>)} */}
                    <SelectWidthAction actionText={['刷新','新建模板']} actions={actions} value={allTempList}/>
                    </Form.Item>                   
                </Form>
            </div>
            <Design
              ref={this.saveDesign}
              cache={false}
              cacheId="zent-design-test"
              confirmUnsavedLeave={false}
              components={groupedComponents}
              value={value}
              onChange={this.onChange}
              //settings={settings}
              //onSettingsChange={this.onSettingsChange}
              scrollTopOffset={-270}
              globalConfig={window._global}                       
            />
          </Card>
        </Spin>
        <div className="xkd-bottom-actions">
          <Button onClick={this.cancel} className="xkd-mr16">取消</Button>
          <Button
            type="primary"
            onClick={this.submit}
            loading={submitLoading}
            disabled={  loading }
          >
            保存
          </Button>          
        </div>       
      </Fragment>
    );
  }
}

export default connect(({ productDetailTemplate, loading, storeinfo }) => ({
    allTempList:productDetailTemplate.allTempList,
    loading: loading.effects['productDetailTemplate/FindTemplateList'], 
    submitLoading: loading.effects['productDetailTemplate/UpdateTemplate'],
    storeinfo: storeinfo,
}))(Simple);
